<template>
    <div class="content-wrapper-view">
        <div class="menu-wrapper">
            <el-row>
                <el-col :span="4" class="tree-box">
                    <div class="tree-box-header">
                        地区
                    </div>
                    <div class="tree-box-body" :style="`overflow-y: auto;max-height: ${wrapperHeight-200}px`">
                        <el-tree
                            :props="defaultProps"
                            :load="loadNode"
                            node-key="id" ref="tree" 
                            v-loading="loadingTree"
                            highlight-current 
                            @node-click="handleNodeClick"
                            lazy>
                        </el-tree>
                    </div>
                </el-col>

                <el-col :span="20" class="content-box">
                    <el-row>
                        <el-col>
                            <div class="btn-wrapper">
                                <el-button type="primary" size="medium" icon="el-icon-plus" @click="handleCreate">添加</el-button>
                                <el-button type="primary" size="medium" icon="el-icon-edit" @click="handleUpdate">修改</el-button>
                                <el-button type="danger" size="medium" icon="el-icon-delete" @click="handleDelete">删除</el-button>
                                <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="handleResetFilter">刷新</el-button>
                                <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="handleGenerateJSON">生成Vant JSON</el-button>
                            </div>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col>
                            <div class="detail-wrapper">
                                <div class="area-info">
                                    <span v-if="detail.name">地区：{{detail.name}}</span>
                                    <span v-if="detail.code">编码：{{detail.code}}</span>
                                    <span v-if="detail.code">经度：{{lat}}</span>
                                    <span v-if="detail.code">纬度：{{lng}}</span>
                                    <span v-if="currentLocation"><el-icon class="el-icon-location"></el-icon> 当前位置：{{currentLocation}}</span>
                                </div>
                                <div class="toolbar">
                                    <el-button type="primary" size="small" icon="el-icon-mars-reset" @click="geolocation">定位</el-button>
                                </div>

                                <div id="container" class="map-container" :style="`height: ${wrapperHeight-300}px`"></div>
                            </div>
                        </el-col>
                    </el-row>

                </el-col>
            </el-row>

            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleDialogClose">
                <el-row>
                    <el-col :span="6" style="overflow-y: auto;height: 400px">
                        <el-tree
                            :props="defaultProps"
                            :load="loadNode"
                            node-key="id" 
                            ref="tree2" 
                            v-loading="loadingTreeDialog"
                            highlight-current 
                            @node-click="handleNodeClickDialog"
                            lazy>
                        </el-tree>
                    </el-col>

                    <el-col :span="18">
                        <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                            <el-form-item label="所属上级">
                                <el-input v-model="form.parentName" placeholder="请选择所属上级" readonly style="width: 90%;">
                                    <i class="el-icon-close el-input__icon" slot="suffix" @click="handleIconRemoveClick"></i>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="地区名称" prop="name">
                                <el-input v-model="form.name" placeholder="地区名称" style="width: 90%;"></el-input>
                            </el-form-item>
                            <el-form-item label="层级" prop="level">
                                <el-radio-group v-model="form.level">
                                    <el-radio :label="1" border size="medium">一级</el-radio>
                                    <el-radio :label="2" border size="medium">二级</el-radio>
                                    <el-radio :label="3" border size="medium">三级</el-radio>
                                    <el-radio :label="4" border size="medium">四级</el-radio>
                                </el-radio-group>
                                <el-button type="danger" size="mini" icon="el-icon-close" circle @click="handleClearLevel" style="margin-left:10px;"></el-button>
                            </el-form-item>

                        </el-form>
                    </el-col>
                </el-row>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancel('form')">取 消</el-button>
                    <el-button v-if="dialogStatus == 'create'" type="primary" @click="create('form')">确 定</el-button>
                    <el-button v-else type="primary" @click="update('form')">确 定</el-button>
                </div>
            </el-dialog>

        </div>
    </div>
</template>

<script>
import {
    created,
    updated,
    deleted,
    selectOne,
    selectList,
    selectTree,
    loadAreaRoot,
    loadAreaByPid,
    updateLocation,
    asyncGeneratorVantAreaJson
} from "@/api/system/area/Area";

import valid from "@/libs/rules";

let map, marker, geolocation, district, polygons = [];
export default {
    name: "Area",
    data() {
        let required = valid.required();
        return {
            loadingTree: true,
            loadingTreeDialog: false,
            dialogFormVisible: false,
            dialogStatus: "",
            textMap: {
                update: "编辑",
                create: "创建",
            },
            defaultProps: {
                label: "name",
                children: "children",
                isLeaf: 'leaf'
            },
            form: {
                parentName: null
            },
            detail: {},
            rules: {
                example: [required]
            },
            currentLocation: null,
            lat: null,
            lng: null,

            wrapperHeight: document.documentElement.clientHeight
        };
    },
    mounted() {
        this.$nextTick(function() {
            this.initMap();
        });
    },
    methods: {
        initMap() { //初始化地图
            let _this = this
            map = new AMap.Map("container", {
                resizeEnable: true, //是否监控地图容器尺寸变化
                zoom: 4
            });
            map.on("complete", function() {
                _this.geolocation()
                _this.initDistrictSearch()
            });
        },
        initDistrictSearch() { //初始化行政区查询对象
            AMap.plugin("AMap.DistrictSearch", function() {
                // 创建行政区查询对象
                district = new AMap.DistrictSearch({
                    extensions: 'all',      // 返回行政区边界坐标等具体信息
                    subdistrict: 0,         //获取边界不需要返回下级行政区
                    extensions: 'all',      //返回行政区边界坐标组等具体信息
                    level: 'district'       //查询行政级别为 市
                })
            })
        },
        geolocation() { //定位
            let _this = this
            AMap.plugin("AMap.Geolocation", function() {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, //是否使用高精度定位，默认:true
                    timeout: 10000, //超过10秒后停止定位，默认：5s
                    buttonPosition: "RB", //定位按钮的停靠位置
                    zoomToAccuracy: true //定位成功后是否自动调整地图视野到定位点
                });
                
                //标签当前位置
                geolocation.getCurrentPosition(function(status, result) {
                    if (status == "complete") {
                        //console.log("complete",result)
                        _this.currentLocation = result.formattedAddress
                        _this.info = JSON.stringify(result)

                        //先删除标记点
                        if (marker) {
                            map.remove(marker);
                        }
                        // 创建一个 Marker 实例：
                        marker = new AMap.Marker({
                            position: result.position,
                            zIndex: 11100
                        });
                        // 将创建的点标记添加到已有的地图实例：
                        marker.setMap(map);
                    } else {
                        console.log("error",result)
                        _this.info = JSON.stringify(result)
                    }
                });

                map.addControl(geolocation);
            });
        },
        searchCity(data) {
            let _this = this
            if('市辖区' !== data.name) {
                district.search(data.name, function(status, result) {
                    map.remove(polygons)//清除上次结果
                    polygons = [];
    
                    _this.lat = result.districtList[0].center.lat
                    _this.lng = result.districtList[0].center.lng

                    //更新坐标
                    _this.handleUpdateLcation(data.id, _this.lat, _this.lng)
    
                    // 获取朝阳区的边界信息
                    var bounds = result.districtList[0].boundaries
                    if (bounds) {
                        for (var i = 0, l = bounds.length; i < l; i++) {
                            //生成行政区划polygon
                            var polygon = new AMap.Polygon({
                                strokeWeight: 1,
                                path: bounds[i],
                                fillOpacity: 0.4,
                                fillColor: '#80d8ff',
                                strokeColor: '#0091ea'
                            });
                            polygons.push(polygon)
                        }
                        map.add(polygons)
                        map.setFitView(polygons);//视口自适应
                    }
                })
            }
        },
        handleUpdateLcation(id, latitude, longitude) { //更新坐标
            updateLocation({id, latitude, longitude}).then(response => {
                console.log(response)
            })
        },
        loadNode(node, resolve) { //异步加载Tree
            if (node.level === 0) {
                loadAreaRoot().then(response => {
                    this.loadingTree = false
                    return resolve(response.data.data);
                })
            } else {
                loadAreaByPid({pid: node.data.id}).then(response => {
                    resolve(response.data.data);
                })
            }
        },
        handleNodeClick(data, node) {
            //从地图上显示该区域
            this.searchCity(node.data)

            selectOne(node.data.id).then(response => {
                this.detail = Object.assign({}, response.data.data);
                if(node.parent.data !== undefined) {
                    this.detail.parentName = node.parent.data.name;
                } 
            });
        },
        handleClearLevel() {
            this.form.level = null;
        },
        handleNodeClickDialog(data, node) {
            var shut = false;
            var sf = this.form;

            //新增菜单
            if (sf.id == undefined) {
                this.form = Object.assign({}, this.form);
                this.form.pid = node.data.id;
                this.form.parentName = node.data.name;
                return;
            }

            //新增菜单时不执行以下程序
            //修改时上级选择错误，默认的父级菜单
            let parentNode = null;
            if (sf.id) {
                //parentNode = this.$refs.tree.getNode(sf.id).parent.data;
            }

            
            //判断是否选择自己作为上级
            if (this.form.id == data.id) {
                if (parentNode) {
                    //选择默认父级菜单
                    this.form.pid = parentNode.id;
                    this.form.parentName = parentNode.name;
                } else {
                    this.form.pid = null;
                    this.form.parentName = null;
                }
                this.$message({
                    title: "提示",
                    message: "选择所属上级有误",
                    type: "info",
                    duration: 2000
                });
                return;
            }
            
            //判断选择的上级是否当前修改的上级
            res(node);
            function res(node) {
                if (!shut) {
                    var n = node.parent;
                    if (null != n.parent) {
                        if (sf.id == n.data.id || sf.id == n.data.pid) {
                            shut = true;
                        }
                        res(n);
                    }
                }
            }
            
            if (shut == true) {
                if (parentNode) {
                    //选择默认父级菜单
                    this.form.pid = parentNode.id;
                    this.form.parentName = parentNode.name;
                } else {
                    //
                    this.form.pid = null;
                    this.form.parentName = null;
                }
                this.$message({
                    title: "提示",
                    message: "选择所属上级有误",
                    type: "warning",
                    duration: 2000
                });
                return;
            }

            this.form = Object.assign({}, this.form);
            this.form.pid = node.data.id;
            this.form.parentName = node.data.name;
        },
        handleIconRemoveClick() {
            this.form.pid = null;
            this.form.parentName = null;
        },
        handleDialogClose() {
            //关闭窗口回调函数
            this.cancel("form");
        },
        handleResetFilter() {
            //重置过滤条件
            this.detail = {};
        },

        handleCreate() {
            //添加数据窗口
            this.dialogStatus = "create";
            this.dialogFormVisible = true;
        },
        handleUpdate() {
            //修改数据窗口
            if (this.detail.id) {
                selectOne(this.detail.id).then(response => {
                    this.dialogStatus = "update";
                    this.dialogFormVisible = true;
                    this.form = Object.assign({}, response.data.data);

                    let parentNode = this.$refs.tree.getNode(this.form.id).parent.data;

                    if (parentNode) {
                        this.form.pid = parentNode.id;
                        this.form.parentName = parentNode.name;
                    }
                });
            } else {
                this.$notify({
                    title: "提示",
                    message: "请选择需要修改的记录",
                    type: "warning",
                    duration: 2000
                });
            }
        },
        handleDelete() {
            //批量删除数据
            if (this.detail.id) {
                this.$confirm("确定要删除？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        deleted(this.detail.id).then(response => {
                            if (response.data.status === 200) {
                                this.$notify({
                                    title: "提示",
                                    message: "删除成功",
                                    type: "success",
                                    duration: 2000
                                });
                                this.handleResetFilter();
                            } else {
                                this.$notify({
                                    title: "删除失败",
                                    message: response.data.msg,
                                    type: "error",
                                    duration: 2000
                                });
                            }
                        });
                    })
                    .catch(() => {});
            } else {
                this.$notify({
                    title: "提示",
                    message: "请选择需要删除的记录",
                    type: "warning",
                    duration: 2000
                });
            }
        },
        create(formName) {
            //添加数据
            const set = this.$refs;
            set[formName].validate(valid => {
                if (valid) {
                    created(this.form).then(response => {
                        if (response.data.status === 200) {
                            this.$notify({
                                title: "提示",
                                message: "添加成功",
                                type: "success",
                                duration: 2000
                            });
                            this.handleResetFilter();
                        } else {
                            this.$notify({
                                title: "操作失败",
                                message: response.data.msg,
                                type: "error",
                                duration: 2000
                            });
                        }
                        this.dialogFormVisible = false;
                    });
                }
            });
        },
        update(formName) {
            //修改数据
            const set = this.$refs;
            set[formName].validate(valid => {
                if (valid) {
                    updated(this.form).then(response => {
                        if (response.data.status === 200) {
                            this.$notify({
                                title: "提示",
                                message: "修改成功",
                                type: "success",
                                duration: 2000
                            });
                            this.detail = Object.assign({}, this.form);
                        } else {
                            this.$notify({
                                title: "发生错误",
                                message: response.data.msg,
                                type: "error",
                                duration: 2000
                            });
                        }
                        this.dialogFormVisible = false;
                    });
                }
            });
        },
        handleGenerateJSON(){
            asyncGeneratorVantAreaJson().then(response => {
                if (response.data.status === 200) {
                    this.$notify({
                        title: "提示",
                        message: "生成成功",
                        type: "success",
                        duration: 2000
                    });
                } else {
                    this.$notify({
                        title: "发生错误",
                        message: response.data.msg,
                        type: "error",
                        duration: 2000
                    });
                }
            })
        },

        cancel(formName) {
            this.dialogFormVisible = false;
            const set = this.$refs;
            set[formName].resetFields();
            this.form = {
                parentName: null
            };
        }
    }
};
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
.menu-wrapper {
    border: 1px solid #e9eaec;
    background: #fff;
    border-radius: 4px;
    font-size: 14px;
    position: relative;
    -webkit-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out;
    &:hover {
        border-color: #eee;
        box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
    }
    .tree-box {
        border-right: 1px solid #dcdcdc;
        min-height: 600px;
        &-header {
            padding-left: 10px;
            height: 50px;
            line-height: 50px;
            border-bottom: 1px solid #dcdcdc;
        }
        &-body {
        }
    }

    .content-box {
        
        .btn-wrapper {
            padding-left: 10px;
            line-height: 50px;
            border-bottom: 1px solid #dcdcdc;
        }

        .detail-wrapper {
            padding: 15px;
            .area-info{
                margin-bottom: 10px;
                span{
                    margin-right: 20px;
                }
            }
            .toolbar{
                margin-bottom: 10px;
            }
            .map-container{
                width: 100%;
            }
        }

        .permission-wrapper {
            padding: 10px;
            margin-top: 10px;
            margin-bottom: 10px;
        }
    }
}
</style>